package com.campus.help.service.impl;

import com.campus.help.common.Result;
import com.campus.help.common.ResultCode;
import com.campus.help.dto.AdminLoginDTO;
import com.campus.help.entity.Admin;
import com.campus.help.mapper.AdminMapper;
import com.campus.help.service.AdminService;
import com.campus.help.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理员服务实现类
 */
@Slf4j
@Service
public class AdminServiceImpl implements AdminService {
    
    @Autowired
    private AdminMapper adminMapper;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    private static final String SALT = "campus-help-admin-salt";
    
    @Override
    public Result login(AdminLoginDTO loginDTO) {
        // 参数验证
        if (!StringUtils.hasText(loginDTO.getUsername()) || !StringUtils.hasText(loginDTO.getPassword())) {
            return Result.error(ResultCode.PARAM_ERROR);
        }
        
        // 根据用户名查询管理员
        Admin admin = adminMapper.selectByUsername(loginDTO.getUsername());
        if (admin == null) {
            return Result.error(ResultCode.LOGIN_ERROR);
        }
        
        // 验证密码
        String encryptedPassword = encryptPassword(loginDTO.getPassword());
        if (!encryptedPassword.equals(admin.getPassword())) {
            return Result.error(ResultCode.LOGIN_ERROR);
        }
        
        // 检查账号状态
        if (admin.getStatus() != 1) {
            return Result.error(ResultCode.ACCOUNT_DISABLED);
        }
        
        try {
            // 生成JWT token
            String token = jwtUtils.generateAdminToken(admin.getId(), admin.getUsername(), admin.getRole());
            
            // 更新最后登录时间
            updateLastLoginTime(admin.getId());
            
            // 返回登录结果
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("adminInfo", buildAdminInfo(admin));
            
            return Result.success(data);
            
        } catch (Exception e) {
            log.error("管理员登录失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR);
        }
    }
    
    @Override
    public Admin getByUsername(String username) {
        return adminMapper.selectByUsername(username);
    }
    
    @Override
    public Admin getById(Long id) {
        return adminMapper.selectById(id);
    }
    
    @Override
    public void updateLastLoginTime(Long adminId) {
        adminMapper.updateLastLoginTime(adminId);
    }
    
    @Override
    public boolean updatePassword(Long adminId, String newPassword) {
        try {
            int result = adminMapper.updatePassword(adminId, newPassword, adminId);
            return result > 0;
        } catch (Exception e) {
            log.error("更新管理员密码失败: adminId={}", adminId, e);
            return false;
        }
    }
    
    @Override
    public Map<String, Object> getSystemStats() {
        try {
            // 获取基础统计数据
            Map<String, Object> stats = adminMapper.getAdminStats();
            
            if (stats == null) {
                stats = new HashMap<>();
            }
            
            // 如果数据库中没有统计数据，返回默认值
            stats.putIfAbsent("totalUsers", 0);
            stats.putIfAbsent("totalMerchants", 0);
            stats.putIfAbsent("totalLabors", 0);
            stats.putIfAbsent("todayNewUsers", 0);
            stats.putIfAbsent("todayNewLabors", 0);
            stats.putIfAbsent("activeUsers", 0);
            stats.putIfAbsent("pendingLabors", 0);
            stats.putIfAbsent("completedLabors", 0);
            
            return stats;
        } catch (Exception e) {
            log.error("获取系统统计信息失败", e);
            // 返回默认统计数据
            Map<String, Object> defaultStats = new HashMap<>();
            defaultStats.put("totalUsers", 0);
            defaultStats.put("totalMerchants", 0);
            defaultStats.put("totalLabors", 0);
            defaultStats.put("todayNewUsers", 0);
            defaultStats.put("todayNewLabors", 0);
            defaultStats.put("activeUsers", 0);
            defaultStats.put("pendingLabors", 0);
            defaultStats.put("completedLabors", 0);
            return defaultStats;
        }
    }
    
    @Override
    public Map<String, Object> getAdminList(int page, int size, String keyword, Integer role, Integer status) {
        try {
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Admin> pageParam = 
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, size);
            
            com.baomidou.mybatisplus.core.metadata.IPage<Admin> adminPage = 
                adminMapper.selectAdminPage(pageParam, keyword, role, status);
            
            Map<String, Object> result = new HashMap<>();
            result.put("records", adminPage.getRecords());
            result.put("total", adminPage.getTotal());
            result.put("current", adminPage.getCurrent());
            result.put("size", adminPage.getSize());
            result.put("pages", adminPage.getPages());
            
            return result;
        } catch (Exception e) {
            log.error("获取管理员列表失败", e);
            throw new RuntimeException("获取管理员列表失败");
        }
    }
    
    @Override
    public boolean updateAdminStatus(Long adminId, Integer status, Long updateBy) {
        try {
            int result = adminMapper.updateStatus(adminId, status, updateBy);
            return result > 0;
        } catch (Exception e) {
            log.error("更新管理员状态失败: adminId={}, status={}", adminId, status, e);
            return false;
        }
    }
    
    @Override
    public boolean resetPassword(Long adminId, Long updateBy) {
        try {
            // 默认密码
            String defaultPassword = encryptPassword("123456");
            int result = adminMapper.resetPassword(adminId, defaultPassword, updateBy);
            return result > 0;
        } catch (Exception e) {
            log.error("重置管理员密码失败: adminId={}", adminId, e);
            return false;
        }
    }
    
    /**
     * 构建管理员信息（脱敏）
     */
    private Map<String, Object> buildAdminInfo(Admin admin) {
        Map<String, Object> adminInfo = new HashMap<>();
        adminInfo.put("id", admin.getId());
        adminInfo.put("username", admin.getUsername());
        adminInfo.put("name", admin.getName());
        adminInfo.put("email", admin.getEmail());
        adminInfo.put("phone", admin.getPhone());
        adminInfo.put("role", admin.getRole());
        return adminInfo;
    }
    
    /**
     * 密码加密
     */
    private String encryptPassword(String password) {
        return DigestUtils.md5DigestAsHex((password + SALT).getBytes());
    }
}
